﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using MiddlewareCore.Middleware;
using MiddlewareCore.Services;

namespace MiddlewareCore.Application
{
    public static class ApplicationExtesion
    {
        /// <summary>
        /// 添加中间件
        /// </summary>
        /// <typeparam name="T">IMiddleware实现类</typeparam>
        /// <param name="app">IApplicationBuilder</param>
        public static IApplicationBuilder UseMiddleware<T>(this IApplicationBuilder app) where T : class
        {
            Type type = typeof(T);
            TypeInfo typeInfo = type.GetTypeInfo();
            if (!typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(typeInfo))
                return app;
            try
            {
                app.Use((next) => async (context) =>
                {
                    IMiddleware middleware = Activator.CreateInstance(type, next) as IMiddleware;
                    await middleware.Invoke(context);
                });
            }
            catch { }
            return app;
        }
        /// <summary>
        /// 执行启动类里中间件
        /// </summary>
        /// <typeparam name="TStartUp">IStartUp实现类</typeparam>
        /// <param name="app">IApplicationBuilder</param>
        /// <returns></returns>
        public static IApplicationBuilder UseStartUp<TStartUp>(this IApplicationBuilder app) where TStartUp : IStartUp
        {
            try
            {
                IStartUp startUp = Activator.CreateInstance(typeof(TStartUp)) as IStartUp;
                startUp.Configure(app);
                
            }
            catch { }
            return app;
        }
    }
}
